package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SignonServlet extends HttpServlet {
    private static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = request.getSession();
        AccountService accountService = new AccountService();
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Account account =  accountService.getAccount(username,password);
        if (account == null){
            session.setAttribute("message","The entered account number was not found.");
            request.getRequestDispatcher(ERROR).forward(request,response);
        }
        else {
            session.setAttribute("account", account);
            request.getRequestDispatcher(MAIN).forward(request, response);
        }
    }
}
